#include"app_Modbus.h"

modbus_t *modbus;

/// @brief 初始化modbus
/// @param  
/// @return 
Com_state_t app_Modbus_init(void)
{
    //创建rtu
    modbus = modbus_new_rtu("/dev/ttyS1",115200,'N',8,1);
    
    if(modbus == NULL)
    {
        log_error("创建modbus上下文失败");
        return Com_FAIL;
    }

    if (modbus_connect(modbus) == -1)
    {
        log_error("modbus连接失败");
        modbus_free(modbus);//释放modbus
        return Com_FAIL;
    }

    return Com_OK;
}

/// @brief 写入速率
/// @param slave_addr 
/// @param speed 
/// @return 
Com_state_t app_Modbus_write_single_holde_register(uint8_t slave_addr,uint16_t speed)
{
    log_debug("slave_addr:%d,speed:%d",slave_addr,speed);
    modbus_set_slave(modbus,slave_addr);//设置从机地址
    int status = modbus_write_register(modbus,0,speed);//写入寄存器
    if(status == -1)
    {
        log_error("写入失败");
        return Com_FAIL;
    }

    log_info("写入成功");
    return Com_OK;
}


/// @brief 读取速率
/// @param slave_addr 
/// @param speed 
/// @return 
Com_state_t app_Modbus_read_single_input_register(uint8_t slave_addr,uint16_t *speed)
{
    modbus_set_slave(modbus,slave_addr);//设置从机地址
    int status = modbus_read_input_registers(modbus,0,1,speed);//写入寄存器
    if(status == -1)
    {
        log_error("读取失败");
        return Com_FAIL;
    }

    log_info("读取成功");
    return Com_OK;
}